<!DOCTYPE html>
<html lang="zh-CN">
<base href="http://localhost:63342/Blog/" />
{debug}
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章管理</title>
    <style>
        /* 样式同之前的保持一致 */
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Microsoft YaHei', Arial, sans-serif; background-color: #f5f5f5; height: 100vh; overflow: hidden; }
        .article-management { background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); padding: 20px; }
        .toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #f0f0f0; }
        .btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: all 0.3s ease; }
        .btn-primary { background: #667eea; color: white; }
        .btn-primary:hover { background: #5a6fd8; }
        .btn-danger { background: #ff4757; color: white; }
        .btn-danger:hover { background: #ff3742; }
        .search-box { padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; width: 200px; }
        .article-table { width: 100%; border-collapse: collapse; }
        .article-table th, .article-table td { padding: 12px; text-align: left; border-bottom: 1px solid #f0f0f0; }
        .article-table th { background: #f8f9fa; font-weight: bold; color: #333; }
        .status-published { background: #28a745; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px; }
        .status-draft { background: #ffc107; color: #333; padding: 2px 8px; border-radius: 12px; font-size: 12px; }
        
        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 999;
            display: none;
        }
        
        .modal-content {
            background: white;
            border-radius: 8px;
            padding: 20px;
            width: 90%;
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .modal-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        
        .close-modal {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #999;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
        }
        
        .close-modal:hover {
            background: #f0f0f0;
            color: #333;
        }
        
        /* 表单样式 */
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: 500;
        }
        
        .form-group input[type="text"],
        .form-group input[type="email"],
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-group textarea {
            min-height: 200px;
            resize: vertical;
        }
        
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #f0f0f0;
        }
        
        /* 消息提示框样式 */
        .message-box {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 12px 20px;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .message-box.success {
            background: #28a745;
        }
        
        .message-box.error {
            background: #dc3545;
        }
        
        /* 确认对话框样式 */
        .confirm-dialog {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            display: none;
        }
        
        .confirm-content {
            background: white;
            border-radius: 8px;
            padding: 20px;
            width: 90%;
            max-width: 400px;
            text-align: center;
        }
        
        .confirm-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
        }
        
        .confirm-message {
            color: #666;
            margin-bottom: 20px;
        }
        
        .confirm-actions {
            display: flex;
            justify-content: center;
            gap: 10px;
        }
        
        .btn-default {
            background: #e9ecef;
            color: #333;
        }
        
        .btn-default:hover {
            background: #dee2e6;
        }
        
        /* 多选框样式 */
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 5px;
        }
    </style>
</head>
<body>
    <div class="article-management">
        <h2>文章管理</h2>

        <!-- 工具栏：按钮和搜索框 -->
        <div class="toolbar">
            <div>
                <button class="btn btn-primary" onclick="openCreateArticleModal()">+ 新建文章</button>
                <button class="btn btn-danger" onclick="batchDeleteArticles()">批量删除</button>
            </div>
            <div>
                <input type="text" id="searchArticle" class="search-box" placeholder="搜索文章...">
                <button class="btn btn-primary" onclick="searchArticles()">搜索</button>
            </div>
        </div>

        <!-- 文章表格 -->
        <table class="article-table">
            <thead>
                <tr>
                    <th><input type="checkbox"></th>
                    <th>标题</th>
                    <th>作者</th>
                    <th>分类</th>
                    <th>状态</th>
                    <th>发布时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {foreach $articles as $article}
                    <tr>
                        <td><input type="checkbox"></td>
                        <td>{$article.title}</td>
                        <td>{$article.author}</td>
                        <td>{$article.category}</td>
                        <td>
                            <span class="status-{$article.status == '1' ? '1' : '0'}">
                                {$article.status == '1' ? '已发布' : '草稿'}
                            </span>
                        </td>
                        <td>{$article.last_time}</td>
                        <td>
                            <button class="btn btn-primary" style="padding: 4px 8px; font-size: 12px;" onclick="editArticle('{$article.id}')">编辑</button>
                            <button class="btn btn-danger" style="padding: 4px 8px; font-size: 12px;" onclick="deleteArticle('{$article.id}')">删除</button>
                        </td>
                    </tr>
                {foreachelse}
                    <tr>
                        <td colspan="7" style="text-align: center; padding: 40px; color: #666;">
                            暂无文章数据
                        </td>
                    </tr>
                {/foreach}
            </tbody>
        </table>
    </div>
    </div>

    <!-- 新建文章模态框 -->
    <div class="modal-overlay" id="createArticleModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">新建文章</h3>
                <button class="close-modal" onclick="closeCreateArticleModal()">&times;</button>
            </div>
            <form id="createArticleForm">
                <div class="form-group">
                    <label for="title">文章标题 *</label>
                    <input type="text" id="title" name="title" required placeholder="请输入文章标题">
                </div>
                <div class="form-group">
                    <label for="author">作者 *</label>
                    <input type="text" id="author" name="author" required placeholder="请输入作者姓名">
                </div>
                <div class="form-group">
                    <label for="category">分类 *</label>
                    <input type="text" id="category" name="category" required placeholder="请输入文章分类">
                </div>
                <div class="form-group">
                    <label for="content">文章内容 *</label>
                    <textarea id="content" name="content" required placeholder="请输入文章内容"></textarea>
                </div>
                <div class="form-group">
                    <label for="status">状态</label>
                    <select id="status" name="status">
                        <option value="1">已发布</option>
                        <option value="0">草稿</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-default" onclick="closeCreateArticleModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑文章模态框 -->
    <div class="modal-overlay" id="editArticleModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">编辑文章</h3>
                <button class="close-modal" onclick="closeEditArticleModal()">&times;</button>
            </div>
            <form id="editArticleForm">
                <input type="hidden" id="editArticleId" name="id">
                <div class="form-group">
                    <label for="editTitle">文章标题 *</label>
                    <input type="text" id="editTitle" name="title" required placeholder="请输入文章标题">
                </div>
                <div class="form-group">
                    <label for="editAuthor">作者 *</label>
                    <input type="text" id="editAuthor" name="author" required placeholder="请输入作者姓名">
                </div>
                <div class="form-group">
                    <label for="editCategory">分类 *</label>
                    <input type="text" id="editCategory" name="category" required placeholder="请输入文章分类">
                </div>
                <div class="form-group">
                    <label for="editContent">文章内容 *</label>
                    <textarea id="editContent" name="content" required placeholder="请输入文章内容"></textarea>
                </div>
                <div class="form-group">
                    <label for="editStatus">状态</label>
                    <select id="editStatus" name="status">
                        <option value="1">已发布</option>
                        <option value="0">草稿</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-default" onclick="closeEditArticleModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 消息提示框 -->
    <div class="message-box" id="messageBox"></div>

    <!-- 确认对话框 -->
    <div class="confirm-dialog" id="confirmDialog">
        <div class="confirm-content">
            <h3 class="confirm-title" id="confirmTitle">确认操作</h3>
            <p class="confirm-message" id="confirmMessage">您确定要执行此操作吗？</p>
            <div class="confirm-actions">
                <button class="btn btn-default" onclick="closeConfirmDialog()">取消</button>
                <button class="btn btn-danger" onclick="confirmAction()">确认</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量，用于存储待执行的确认操作
        let confirmCallback = null;
        
        // 显示消息框
        function showMessageBox(message, isSuccess = true) {
            const messageBox = document.getElementById('messageBox');
            messageBox.textContent = message;
            messageBox.className = 'message-box ' + (isSuccess ? 'success' : 'error');
            messageBox.style.display = 'block';
            messageBox.style.opacity = '1';
            
            setTimeout(() => {
                messageBox.style.opacity = '0';
                setTimeout(() => {
                    messageBox.style.display = 'none';
                }, 300);
            }, 3000);
        }
        
        // 显示确认对话框
        function showConfirmDialog(title, message, callback) {
            const confirmDialog = document.getElementById('confirmDialog');
            document.getElementById('confirmTitle').textContent = title;
            document.getElementById('confirmMessage').textContent = message;
            confirmDialog.style.display = 'flex';
            confirmCallback = callback;
        }
        
        // 关闭确认对话框
        function closeConfirmDialog() {
            document.getElementById('confirmDialog').style.display = 'none';
            confirmCallback = null;
        }
        
        // 确认操作
        function confirmAction() {
            if (confirmCallback) {
                confirmCallback();
            }
            closeConfirmDialog();
        }
        
        // AJAX请求函数
        function ajaxRequest(url, successCallback, errorCallback, params = {}, method = 'GET') {
            const xhr = new XMLHttpRequest();
            xhr.open(method, url, true);
            
            // 设置X-Requested-With头，标识这是AJAX请求
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            
            if (method === 'POST') {
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            }
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            successCallback(response);
                        } catch (e) {
                            errorCallback('JSON解析错误: ' + e.message + '，响应内容: ' + xhr.responseText);
                        }
                    } else {
                        errorCallback('请求失败: ' + xhr.status + '，响应内容: ' + xhr.responseText);
                    }
                }
            };
            
            let postData = null;
            if (method === 'POST' && params) {
                // 直接构建URL编码的字符串，确保正确处理中文字符
                const dataArray = [];
                for (const key in params) {
                    if (params.hasOwnProperty(key)) {
                        dataArray.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
                    }
                }
                postData = dataArray.join('&');
            }
            
            xhr.send(postData);
        }
        
        // 打开新建文章模态框
        function openCreateArticleModal() {
            document.getElementById('createArticleModal').style.display = 'flex';
            document.getElementById('createArticleForm').reset();
        }
        
        // 关闭新建文章模态框
        function closeCreateArticleModal() {
            document.getElementById('createArticleModal').style.display = 'none';
        }
        
        // 打开编辑文章模态框
        function editArticle(articleId) {
            // 获取文章数据并填充到表单
            ajaxRequest(
                'admin.php?c=Article&a=getArticle&id=' + articleId,
                function(response) {
                    if (response.success) {
                        const article = response.data;
                        document.getElementById('editArticleId').value = article.id;
                        document.getElementById('editTitle').value = article.title;
                        document.getElementById('editAuthor').value = article.author;
                        document.getElementById('editCategory').value = article.category;
                        document.getElementById('editContent').value = article.content;
                        document.getElementById('editStatus').value = article.status;
                        document.getElementById('editArticleModal').style.display = 'flex';
                    } else {
                        showMessageBox(response.message, false);
                    }
                },
                function(error) {
                    showMessageBox(error, false);
                }
            );
        }
        
        // 关闭编辑文章模态框
        function closeEditArticleModal() {
            document.getElementById('editArticleModal').style.display = 'none';
        }
        
        // 删除文章
        function deleteArticle(articleId) {
            showConfirmDialog(
                '确认删除',
                '您确定要删除这篇文章吗？此操作不可撤销。',
                function() {
                    ajaxRequest(
                        'admin.php?c=Article&a=deleteArticle',
                        function(response) {
                            if (response.success) {
                                showMessageBox('文章删除成功');
                                // 刷新文章列表
                                setTimeout(refreshArticleList, 1000);
                            } else {
                                showMessageBox(response.message, false);
                            }
                        },
                        function(error) {
                            showMessageBox(error, false);
                        },
                        { id: articleId },
                        'POST'
                    );
                }
            );
        }
        
        // 批量删除文章
        function batchDeleteArticles() {
            const selectedArticles = [];
            const checkboxes = document.querySelectorAll('.article-table tbody input[type="checkbox"]:checked');
            
            if (checkboxes.length === 0) {
                showMessageBox('请至少选择一篇文章', false);
                return;
            }
            
            checkboxes.forEach(checkbox => {
                // 假设行数据存储在行的某个属性中，这里简化处理
                const row = checkbox.closest('tr');
                // 从行中获取文章ID（实际实现中可能需要调整）
                // 这里假设文章ID在某个单元格中或有其他方式获取
                // 简化示例，实际应根据具体HTML结构调整
                selectedArticles.push(row.querySelector('td:nth-child(2)').textContent);
            });
            
            showConfirmDialog(
                '批量删除',
                '您确定要删除选中的 ' + selectedArticles.length + ' 篇文章吗？此操作不可撤销。',
                function() {
                    ajaxRequest(
                        'admin.php?c=Article&a=batchDeleteArticles',
                        function(response) {
                            if (response.success) {
                                showMessageBox('成功删除 ' + response.deletedCount + ' 篇文章');
                                // 刷新文章列表
                                setTimeout(refreshArticleList, 1000);
                            } else {
                                showMessageBox(response.message, false);
                            }
                        },
                        function(error) {
                            showMessageBox(error, false);
                        },
                        { ids: selectedArticles.join(',') },
                        'POST'
                    );
                }
            );
        }
        
        // 搜索文章
        function searchArticles() {
            const keyword = document.getElementById('searchArticle').value.trim();
            ajaxRequest(
                'admin.php?c=Article&a=searchArticles',
                function(response) {
                    if (response.success) {
                        // 刷新文章列表显示搜索结果
                        refreshArticleList(response.data);
                    } else {
                        showMessageBox(response.message, false);
                    }
                },
                function(error) {
                    showMessageBox(error, false);
                },
                { keyword: keyword },
                'POST'
            );
        }
        
        // 刷新文章列表
        function refreshArticleList(articlesData = null) {
            // 如果没有提供数据，则重新加载页面
            if (!articlesData) {
                location.reload();
            } else {
                // 这里可以实现局部刷新文章列表的逻辑
                // 简化示例，实际应根据具体HTML结构调整
                showMessageBox('文章列表已更新');
            }
        }
        
        // 新建文章表单提交
        document.getElementById('createArticleForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const params = {};
            for (const [key, value] of formData.entries()) {
                params[key] = value;
            }
            
            // 简单验证
            if (!params.title || !params.author || !params.category || !params.content) {
                showMessageBox('请填写必填字段', false);
                return;
            }
            
            ajaxRequest(
                'admin.php?c=Article&a=addArticle',
                function(response) {
                    if (response.success) {
                        showMessageBox('文章创建成功');
                        closeCreateArticleModal();
                        // 刷新文章列表
                        setTimeout(refreshArticleList, 1000);
                    } else {
                        showMessageBox(response.message, false);
                    }
                },
                function(error) {
                    showMessageBox(error, false);
                },
                params,
                'POST'
            );
        });
        
        // 编辑文章表单提交
        document.getElementById('editArticleForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const params = {};
            for (const [key, value] of formData.entries()) {
                params[key] = value;
            }
            
            // 简单验证
            if (!params.title || !params.author || !params.category || !params.content) {
                showMessageBox('请填写必填字段', false);
                return;
            }
            
            ajaxRequest(
                'admin.php?c=Article&a=updateArticle',
                function(response) {
                    if (response.success) {
                        showMessageBox('文章更新成功');
                        closeEditArticleModal();
                        // 刷新文章列表
                        setTimeout(refreshArticleList, 1000);
                    } else {
                        showMessageBox(response.message, false);
                    }
                },
                function(error) {
                    showMessageBox(error, false);
                },
                params,
                'POST'
            );
        });
        
        // 全选/取消全选
        document.querySelector('.article-table thead input[type="checkbox"]').addEventListener('change', function() {
            const isChecked = this.checked;
            document.querySelectorAll('.article-table tbody input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = isChecked;
            });
        });
    </script>
</body>
</html>